﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Configuration;

namespace RN.ERP
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SmsService:ISmsService
    {
        [OperationContract]
        public bool Send(string phone, string authCode)
        {
            return SmsBLL.Instance.Send(phone, authCode);
        }
    }

    public class SmsBLL
    {
        /// <summary>
        /// 短信服务的账号
        /// </summary>
        private string Account { set; get; }

        /// <summary>
        /// 短信服务的密码
        /// </summary>
        private string Password { set; get; }

        /// <summary>
        /// 短信模版
        /// </summary>
        private string SmsTemplate { set; get; }

        /// <summary>
        /// 短信服务提供商提供的帮助类
        /// </summary>
        private sms SmsHelper { set; get; }

        private static readonly object locker = new object();

        private static SmsBLL _instance = null;


        private SmsBLL()
        {
            Account = ConfigurationManager.AppSettings["SmsAccount"];
            Password = ConfigurationManager.AppSettings["SmsPwd"];
            SmsTemplate = ConfigurationManager.AppSettings["SmsTemplate"];
            SmsHelper = new sms();
        }

        static SmsBLL()
        {

        }

        public static SmsBLL Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (locker)
                    {
                        if (_instance == null)
                        {
                            _instance = new SmsBLL();
                        }
                    }
                }
                return _instance;
            }
        }

        public bool Send(string phone, string authCode)
        {
            string content = String.Format(SmsTemplate, authCode);
            SubmitResult result = SmsHelper.Submit(Account, Password, phone, content);
            return result.code == 2;
        }
    }
}
